package cn.wolfcode.web.controller;


import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.feign.PayFeginApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by lanxw
 */
@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private PayFeginApi payFeginApi;

    @RequestMapping("/pay")
    public Result<String> pay(String orderNo, Integer type) {
        if (OrderInfo.STATUS_ARREARAGE.equals(type)){
            //在线支付
            String html = orderInfoService.payOnLine(orderNo);
            return Result.success(html);
        }else {
            //积分支付
            orderInfoService.payIntergral(orderNo);
            return Result.success("积分支付成功");
        }
    }

    @RequestMapping("/notify_url")
    public String notifyUrl(@RequestParam Map<String,String> params){
        Result<Boolean> result = payFeginApi.rsaCheckVl(params);//交给支付服务进行验签操作
        if (result == null || result.hasError()) {
            return "fail";
        }
            boolean resultData = result.getData();
            if (resultData){
                //验签成功，获取商户订单编号
                String orderNo = params.get("out_trade_no");
                orderInfoService.paySuccess(orderNo);
            }else {
            //验签失败
            return "fail";
        }
        return "success";
    }



    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;
    @Value("${pay.errorUrl}")
    private String errorUrl;
    @RequestMapping("return_url")
    public void returnUrl(@RequestParam Map<String,String> param,HttpServletResponse response) throws IOException {
        Result<Boolean> result = payFeginApi.rsaCheckVl(param);
        if (result==null||result.hasError()){
            response.sendRedirect(errorUrl);
            return;
        }
        Boolean resultData = result.getData();
        if (resultData){
            String orderNo = param.get("out_trade_no");
            response.sendRedirect(frontEndPayUrl+orderNo);
        }else {
            response.sendRedirect(errorUrl);
            return;
        }
    }


    @RequestMapping("/refund")
    public void refund(String orderNo){
        orderInfoService.refund(orderNo);
    }
}
